﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Cysharp.Threading.Tasks;
using System.Threading;
using System;
using Cysharp.Threading.Tasks.Linq;


//  ***AsAsyncEnumerable 这是UniTask 对Unity的扩展
//   本例 将按钮点击事件 转为异步迭代器
//   然后通过LINQ语法 实现对前3次 点击事件的处理
public class Fourteen : MonoBehaviour
{
    public Button button1;
    public Button button2;
    void Start()
    {
        TripleClick(this.GetCancellationTokenOnDestroy()).Forget();

        ClickTest(this.GetCancellationTokenOnDestroy()).Forget();
    }


    async UniTask TripleClick(CancellationToken token)
    {

        await button1.OnClickAsAsyncEnumerable().Take(3).ForEachAsync(_ =>
        {
            Debug.Log("Every clicked");
        });
        Debug.Log("Three times clicked, complete.");
    }


    async UniTaskVoid ClickTest(CancellationToken token)
    {
        var async1 = button2.OnClickAsAsyncEnumerable();

        await async1.Take(3).ForEachAsync
            ((_, index) =>
        {
            if (token.IsCancellationRequested) return;

            if (index == 0)
            {
                Debug.Log(0);
            }
            else if (index == 1)
            {
                Debug.Log(1);
            }
            else
            {
                Debug.Log(2);
            }


        }, token);

        Debug.Log("All");
    }
}
